// components/location/index.js
import {getLocation, getSetting} from "../../utils/Wx";
import {reverseGeocoder} from "../../utils/Location";

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        loading: {
            type: Boolean,
            value: false
        },
        content: {
            type: String,
            value: ""
        }
    },

    /*
    * 监听
    * */
    observers: {
        "loading": function (val) {
            if (val) {
                this.getLocationRegion();
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _loading: false
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /*
        * 城市区域选择
        * 第一次选择默认获取定位信息
        * 如果失败或者用户拒绝 则跳转城市列表页面选择
        * */
        getLocationRegion: async function () {
            try {
                let value = this.data.content;
                let setting, location, reverse;
                if (!value) {
                    setting = await getSetting("scope.userLocation");
                    if (setting) {
                        this.setData({_loading: true})
                        location = await getLocation();
                        location ? reverse = await reverseGeocoder(location) : null;
                        if (reverse) {
                            this.triggerEvent("location", reverse, {});
                            return true
                        }
                    }
                }
                this.triggerEvent("location", {}, {})
            } catch (e) {
                console.error(e)
                this.triggerEvent("location", {}, {})
            } finally {
                this.setData({_loading: false})
            }
        },
    }
})
